package com.jye.rseven.user.util.queue;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.jye.rseven.domain.TzPtCode;
import com.jye.rseven.service.TyPtCodeService;
import com.jye.rseven.service.TzPtCodeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;

import javax.annotation.PostConstruct;
import java.util.Iterator;
import java.util.List;
//import java.util.concurrent.DelayQueue;
//import java.util.concurrent.ExecutorService;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.ExecutorService;

@Slf4j
@Lazy(false)
@Service
public class DelayOwnOrderServiceImpl implements DelayOrderService<TzPtCode> {

    @Reference
    private TzPtCodeService tzPtCodeService;

    @Reference
    private TyPtCodeService tyPtCodeService;

    @Autowired
    private ExecutorService delayOrderExecutor;

    private final static DelayQueue<ItemDelayed<TzPtCode>> DELAY_QUEUE = new DelayQueue<>();

    /**
     * 初始化时加载数据库中需处理超时的订单
     * 系统启动:扫描数据库中未支付(要在更新时:加上已支付就不用更新了),未过期的的订单
     */
    @PostConstruct
    public void init() {
        log.info("系统启动:扫描数据库中未过期的的订单");
        List<TzPtCode> orderlist = tzPtCodeService.selectFutureOverTimeOrder();
     //   List<TzPtCode> orderList = tzPtCodeService.selectFutureOverTimeOrder();
        for (TzPtCode order : orderlist) {
            ItemDelayed<TzPtCode> orderDelayed = new ItemDelayed<TzPtCode>((long)order.getId(), order.getAddTime().getTime());
            this.addToOrderDelayQueue(orderDelayed);
        }
        log.info("系统启动:扫描数据库中未过期的订单,总共扫描了" + orderlist.size() + "个订单,推入检查队列,准备到期检查...");

        /*启动一个线程，去取延迟订单*/
        delayOrderExecutor.execute(() -> {
            log.info("启动处理的订单线程:" + Thread.currentThread().getName());
            ItemDelayed<TzPtCode> orderDelayed;
            while (true) {
                try {
                    orderDelayed = DELAY_QUEUE.take();
                    //处理超时订单
                    tzPtCodeService.updateCloseOverTimeOrder(orderDelayed.getDataId());//更改团长表得状态
                    //更改团员的状态
                    tyPtCodeService.updatePtStatus(3,tzPtCodeService.findPtById(orderDelayed.getDataId().intValue()).getPtCode());
                } catch (Exception e) {
                    log.error("执行自营超时订单的_延迟队列_异常:" + e);
                }
            }
        });
    }

    /**
     * 加入延迟消息队列
     **/

    @Override
    public boolean addToOrderDelayQueue(ItemDelayed<TzPtCode> itemDelayed) {
        return DELAY_QUEUE.add(itemDelayed);
    }

    /**
     * 加入延迟消息队列
     **/

    @Override
    public boolean addToDelayQueue(TzPtCode order) {
        ItemDelayed<TzPtCode> orderDelayed = new ItemDelayed<>((long)order.getId(), order.getAddTime().getTime());
        return DELAY_QUEUE.add(orderDelayed);    }


    /**
     * 从延迟队列中移除 主动取消就主动从队列中取出
     **/

    @Override
    public void removeToOrderDelayQueue(TzPtCode order) {
        if (order == null) {
            return;
        }
        for (Iterator<ItemDelayed<TzPtCode>> iterator = DELAY_QUEUE.iterator(); iterator.hasNext(); ) {
            ItemDelayed<TzPtCode> queue = iterator.next();
            if (queue.getDataId().equals(order.getId())) {
                DELAY_QUEUE.remove(queue);
            }
        }
    }
}
